/**
 * 
 */
package org.neogenesis.web.loader;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.neogenesis.web.model.Sample;

/**
 * @author fabiofumarola
 *
 */
public abstract class MetaSample implements Iterable<String[]>{
	
	protected Sample sample;
	
	protected String filePath;
	
	protected String platformNameRef;
	
	protected List<String[]> observations;
	
	public MetaSample(String filePath) {
		sample = new Sample();
	}
	
	
	public Sample getSample() {
		return sample;
	}
				
	public String getPlatformNameRef() {
		return platformNameRef;
	}
	
	public void setPlatformNameRef(String platformNameRef) {
		this.platformNameRef = platformNameRef;
	}
	
	public List<String[]> getObservations() throws IOException{
		if (observations != null)
			return observations;
		
		observations = new LinkedList<String[]>();
		BufferedReader in = new BufferedReader(new FileReader(filePath));
		
		String line;
		
		while ((line = in.readLine()) != null){
			observations.add(line.split("\t"));
		}	
		in.close();
		return observations;
	}

	public void setName(String iid) {
		sample.setName(iid);
		
	}
	
	@Override
	public Iterator<String[]> iterator() {
		// TODO Auto-generated method stub
		return new MetaSampleIterator(this);
	}
	
	class MetaSampleIterator implements Iterator<String[]>{
		
		private MetaSample ref;
		
		private String line = null;
		
		private BufferedReader in;
		
		public MetaSampleIterator(MetaSample ref) {
			this.ref = ref;
			try {
				in = new BufferedReader(new FileReader(ref.filePath));
				line = in.readLine();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public boolean hasNext() {
			if (line == null){
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return line != null;
		}

		@Override
		public String[] next() {
			String split[] = line.split("\t");
			try {
				line = in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return split;
		}

		@Override
		public void remove() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
}
